package com.qitianyong.selfclass;

import android.hardware.usb.UsbDeviceConnection;
import android.os.Build;

import com.gkusbsdk.SZUSBCommand;
import com.gkusbsdk.SZUSBFile;
import com.gkusbsdk.SZUSBFileInfo;
import com.gkusbsdk.SZUSBFireware;
import com.gkusbsdk.SZUSBFormat;
import com.gkusbsdk.SZUSBIFrame;
import com.gkusbsdk.SZUSBResolution;
import com.gkusbsdk.SZUSBSDK;
import com.sgkusbcamdemo.CustomApp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.locks.Lock;

/**
 * Created by qitianyong on 2017/3/15.
 * 所有的USB传输从此类走
 * 指令处理通过三个主体线程：
 * 1.插拔状态检测线程
 * 2.基本指令传输线程
 * 3.普通状态检测线程（SD是否存在，录像状态，预览时紧急视频加锁状态和进度）
 */
public class GKDevice extends BaseClass {


    public static GKDevice getInstance() {

        if (__device == null) {
            __device = new GKDevice();
        }

        return __device;
    }

    public GKDevice() {

        __gkusbCmdList = new GKUSBCmdList();
        __thread[CONSTANT.THREAD_ID.ID_COMMAND] = new Thread(commandRunnable);
        __thread[CONSTANT.THREAD_ID.ID_STATUS] = new Thread(statusRunnable);

        __thread[CONSTANT.THREAD_ID.ID_COMMAND].start();
        __thread[CONSTANT.THREAD_ID.ID_STATUS].start();
    }


    private Thread[] __thread = new Thread[CONSTANT.THREAD_ID.ID_COUNT]; // 线程数组

    public static long __hDevice = 0; // 设备句柄
    public static UsbDeviceConnection usbConnection; // USB设备连接
    public static GKDevice __device = null;
    private Lock __lock = CustomApp.__lock;  // 指令发送互斥锁
    private final GKUSBCmdList __gkusbCmdList;


    // 关闭程序
    public void Destroy() {
        //watch dog
        new Thread(new Runnable() {
            @Override
            public void run() {
                PublicMethod.sleep(2000);
                System.exit(0);
            }
        }).start();
        LogUtils.i("GKDevice", "destroy device");
        // 销毁设备
        if (__hDevice != 0) {
            __lock.lock();
            SZUSBSDK.GKUSB_SetProtocol(__hDevice, SZUSBCommand.PROTOCOL_TYPE.TYPE_OLD);
            __lock.unlock();
            releaseDevice();
        }
    }

    public void releaseDevice() {
        __gkusbCmdList.clear();
        __lock.lock();
        if (__hDevice != 0) {
            LogUtils.i("GKDevice", "disconnect---1");
            SZUSBSDK.GKUSB_CloseStream(__hDevice);
            SZUSBSDK.GKUSB_Destroy(__hDevice);
            __hDevice = 0;
            if (usbConnection != null) {
                usbConnection.close();
                usbConnection = null;
            }
            notifyEmptyBusMessage(BUS_MESSAGE.BUS_OFFLINE);
        }
        __lock.unlock();
    }

    // 设置数据流回调
    public void setCallback(SZUSBSDK.CallBack cb) {

        SZUSBSDK.setCallback(cb);
    }

    // 发送USB指令
    public int sendCommand(int command, Object message) {
        if (__hDevice == 0) {
            notifyEmptyBusMessage(BUS_MESSAGE.BUS_PRINT);
            return -1;
        }

        __gkusbCmdList.addCommand(command, message);

        return 0;
    }

    // 发送USB指令
    public int addToFirstNoRepeated(int command, Object message) {
        if (__hDevice == 0) {
            notifyEmptyBusMessage(BUS_MESSAGE.BUS_PRINT);
            return -1;
        }

        __gkusbCmdList.addToFirstNoRepeated(command, message);

        return 0;
    }

    public int clearSpeciallyTypeCommand(int command) {
        if (__hDevice == 0) {
            notifyEmptyBusMessage(BUS_MESSAGE.BUS_PRINT);
            return -1;
        }

        __gkusbCmdList.clearSpeciallyTypeCommand(command);

        return 0;
    }

    // 指令消息的处理
    private void HandleMessage(CommandMessage msg) {

        if (__hDevice == 0 || msg == null) return;
        switch (msg.command) {
            case CONSTANT.COMMAND.CMD_ALL_FORMAT: { // 获取设备支持的格式

            }
            case CONSTANT.COMMAND.CMD_OPEN_STREAM: {// 开启预览
                SZUSBFireware fireware = new SZUSBFireware();
                int ret = SZUSBSDK.GKUSB_GetParam(__hDevice, SZUSBCommand.CMD_RECORD_VERSION, fireware);
                SZUSBResolution objResolution = new SZUSBResolution();

                if (fireware.__product_type == SZUSBCommand.PRODUCT_TYPE.GK8602_A) {
                    objResolution.__width = 1920;
                    objResolution.__height = 1080;
                } else {
                    objResolution.__width = 1280;
                    objResolution.__height = 720;
                }
                SZUSBFormat objFormat = new SZUSBFormat();
                objFormat.__format = SZUSBCommand.STREAM_FORMAT.H264;//GKUSBCommand.STREAM_FORMAT.MJPEG;

                PublicMethod.sleep(200);

                long open = SZUSBSDK.GKUSB_OpenStream(__hDevice, objFormat, objResolution);
                //返回值为-51时，表示格式错误。为兼容老版本 720p A板的设备 ，重新开一次流，参数改为720p
                if (open == -51 && fireware.__product_type == SZUSBCommand.PRODUCT_TYPE.GK8602_A) {
                    objResolution.__width = 1280;
                    objResolution.__height = 720;
                    PublicMethod.sleep(500);
                    open = SZUSBSDK.GKUSB_OpenStream(__hDevice, objFormat, objResolution);
                    if (open == -51) {
                        open = 0;
                    }
                }
                if (open == 0) { // 开启失败后重新检测

                    SZUSBSDK.GKUSB_CloseStream(__hDevice);
                    SZUSBSDK.GKUSB_Destroy(__hDevice);
                    __hDevice = 0;
                    if (usbConnection != null) {

                        usbConnection.close();
                        usbConnection = null;
                    }
                    FindDeviceUtils.findDevice();
                    LogUtils.i("GKDevice", "disconnect---2");
                } else {
                    long time = System.currentTimeMillis();
                    synchronized (SZUSBSDK.notify) {
                        try {
                            SZUSBSDK.notify.wait(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    time = System.currentTimeMillis() - time;
                    System.out.println(time);
                    if (time >= 2900) {
                        SZUSBSDK.GKUSB_CloseStream(__hDevice);
                        openStream();
                        break;
                    }


                    notifyEmptyBusMessage(BUS_MESSAGE.BUS_OPENSTREAM_OK);
                    LogUtils.i("GKDevice", "BUS_OPENSTREAM_OK");
                }
                break;
            }
            case CONSTANT.COMMAND.CMD_GETRECORD_STATUS: { // 获取录像状态

                int status = SZUSBSDK.GKUSB_GetRecordStatus(__hDevice);
                notifyBusMessage(BUS_MESSAGE.BUS_GETRECORD_STATUS, status); // status值-1和STATUS_RECORD
                break;
            }
            case CONSTANT.COMMAND.CMD_SETRECORD_STATUS: { // 设置录像状态

                int status = SZUSBSDK.GKUSB_GetRecordStatus(__hDevice);
                if (status == -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_SETRECORD_STATUS, -1); // status值-1表示失败
                    break;
                }

                status = (status == 0) ? 1 : 0;
                int ret = SZUSBSDK.GKUSB_SetRecordStatus(__hDevice, status);
                notifyBusMessage(BUS_MESSAGE.BUS_SETRECORD_STATUS, ret); // ret为0成功，否则失败
                break;
            }
            case CONSTANT.COMMAND.CMD_SYNC_TIME: { // 时间同步

                int ret = SZUSBSDK.GKUSB_SetParam(__hDevice, SZUSBCommand.CMD_SYNC_TIME, msg.message);
                notifyBusMessage(BUS_MESSAGE.BUS_SYNC_TIME, ret); // ret为0成功，否则失败
                LogUtils.i("System", "CMD_SYNC_TIME" + ret);
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_RECORD_TIME: { // 获取录像时长

                int ret = SZUSBSDK.GKUSB_GetParam(__hDevice, SZUSBCommand.CMD_RECORDTIME_CTRL, null);
                notifyBusMessage(BUS_MESSAGE.BUS_GET_RECORD_TIME, ret); // ret为-1：失败，RESULT_RECORDTIME
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_SENSOR: { // 获取g-sensor等级

                int ret = SZUSBSDK.GKUSB_GetParam(__hDevice, SZUSBCommand.CMD_GSENSOR, null);
                notifyBusMessage(BUS_MESSAGE.BUS_GET_SENSOR, ret); // ret为-1：失败，RESULT_LEVER
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_RECORD_AUTO_MANAL: { // 获取手动/自动录像开关

                int ret = SZUSBSDK.GKUSB_GetParam(__hDevice, SZUSBCommand.CMD_RECORD_AUTO_MANAL, null);
                notifyBusMessage(BUS_MESSAGE.BUS_GET_RECORD_AUTO_MANAL, ret);// ret为-1：失败，GKUSBNormal
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_RECORD_AUDIO: {// 获取录制音频开关

                int ret = SZUSBSDK.GKUSB_GetParam(__hDevice, SZUSBCommand.CMD_AUDIO_RECORD, null);
                notifyBusMessage(BUS_MESSAGE.BUS_GET_RECORD_AUDIO, ret); //ret为-1：失败，SWITCH
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_SDCARD_FORMAT: { // 获取SD卡格式化进度
                int ret = SZUSBSDK.GKUSB_GetParam(__hDevice, SZUSBCommand.CMD_SDFORMAT, null);
                notifyBusMessage(BUS_MESSAGE.BUS_GET_SDCARD_FORMAT, ret); // ret为-1:失败 否则0~100进度
                LogUtils.i("format", "-----ret:" + ret);
                break;
            }
            case CONSTANT.COMMAND.CMD_DEFAULT_FACTORY: { // 恢复出厂设置
                int ret = SZUSBSDK.GKUSB_SetParam(__hDevice, SZUSBCommand.CMD_DEFAULT_FACTORY, null);
                notifyBusMessage(BUS_MESSAGE.BUS_DEFAULT_FACTORY, ret); // ret为-1:失败 否则成功
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_RECORDER_VERSION: { // 获取固件版本
                SZUSBFireware fireware = new SZUSBFireware();
                int ret = SZUSBSDK.GKUSB_GetParam(__hDevice, SZUSBCommand.CMD_RECORD_VERSION, fireware);
                if (ret == -1) {
                    notifyEmptyBusMessage(BUS_MESSAGE.BUS_GET_RECORDER_VERSION_ERR); // 失败
                } else {
                    LogUtils.i("GKDevice", new String(fireware.__version) + " len:" + fireware.__version.length);
                    notifyBusMessage(BUS_MESSAGE.BUS_GET_RECORDER_VERSION_OK, fireware); // 成功，GKUSBFireware
                }
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_RESOLUTION: { // 获取当前分辨率
                int ret = SZUSBSDK.GKUSB_GetParam(__hDevice, SZUSBCommand.CMD_RESOLUTION_CTRL, null);
                notifyBusMessage(BUS_MESSAGE.BUS_GET_RESOLUTION, ret); // -1:失败 否则：RESULT_RESOLUTION
                break;
            }

            case CONSTANT.COMMAND.CMD_GET_CAMERA_SWITCH: { // 获取摄像头
                int ret = SZUSBSDK.GKUSB_GetLiveScreenStatus(__hDevice);
                notifyBusMessage(BUS_MESSAGE.BUS_GET_CAMERA_SWITCH, ret);
                break;
            }
            case CONSTANT.COMMAND.CMD_SET_RECORD_TIME: { // 设置录像时长

                int ret = SZUSBSDK.GKUSB_SetParam(__hDevice, SZUSBCommand.CMD_RECORDTIME_CTRL, msg.message);
                notifyBusMessage(BUS_MESSAGE.BUS_SET_RECORD_TIME, ret); // -1失败，否则成功
                break;
            }
            case CONSTANT.COMMAND.CMD_SET_SENSOR: { // 设置g-sensor等级

                int ret = SZUSBSDK.GKUSB_SetParam(__hDevice, SZUSBCommand.CMD_GSENSOR, msg.message);
                notifyBusMessage(BUS_MESSAGE.BUS_SET_SENSOR, ret); // -1失败，否则成功
                break;
            }
            case CONSTANT.COMMAND.CMD_SET_RECORD_AUTO_MANAL: { // 设置自动/手动录像

                int ret = SZUSBSDK.GKUSB_SetParam(__hDevice, SZUSBCommand.CMD_RECORD_AUTO_MANAL, msg.message);
                notifyBusMessage(BUS_MESSAGE.BUS_SET_RECORD_AUTO_MANAL, ret); // -1失败，否则成功
                break;
            }
            case CONSTANT.COMMAND.CMD_SET_RECORD_AUDIO: { // 设置音频录制开关

                int ret = SZUSBSDK.GKUSB_SetParam(__hDevice, SZUSBCommand.CMD_AUDIO_RECORD, msg.message);
                notifyBusMessage(BUS_MESSAGE.BUS_SET_RECORD_AUDIO, ret);// -1失败，否则成功
                break;
            }
            case CONSTANT.COMMAND.CMD_SET_RESOLUTION: { // 设置分辨率

                int ret = SZUSBSDK.GKUSB_SetParam(__hDevice, SZUSBCommand.CMD_RESOLUTION_CTRL, msg.message);
                notifyBusMessage(BUS_MESSAGE.BUS_SET_RESOLUTION, ret);// -1失败，否则成功
                break;
            }

            case CONSTANT.COMMAND.CMD_SET_CAMERA_SWITCH: { // 设置摄像头

                int ret = SZUSBSDK.GKUSB_SetLiveScreenStatus(__hDevice, (Integer) msg.message);
                notifyBusMessage(BUS_MESSAGE.BUS_SET_CAMERA_SWITCH, ret);// -1失败，否则成功
                break;
            }
            case CONSTANT.COMMAND.CMD_SET_SDCARD_FORMAT: {    // SD卡格式化

                int ret = SZUSBSDK.GKUSB_SetParam(__hDevice, SZUSBCommand.CMD_SDFORMAT, msg.message);
                notifyBusMessage(BUS_MESSAGE.BUS_SET_SDCARD_FORMAT, ret);// -1失败，否则成功

                PublicMethod.sleep(1000); // 格式化指令发送后获取进度需要延时1秒，给设备关闭录像足够时间
                break;
            }
            case CONSTANT.COMMAND.CMD_SEARCH_FILE: { // 搜索所有的文件名
                SZUSBFile[] usbFileArr = new SZUSBFile[CONSTANT.MAX_FILES];
                int count = SZUSBSDK.GKUSB_SearchFileName(__hDevice, (int) msg.message, usbFileArr);
                List<SZUSBFile> gkusbFiles = null;
                if (count != -1) {// -1失败，否则成功
                    gkusbFiles = new ArrayList<>();
                    for (int i = 0; i < count; i++) {
                        usbFileArr[i].__lock = (int) msg.message;
                        gkusbFiles.add(usbFileArr[i]);
                    }
                }
                notifyBusMessage(BUS_MESSAGE.BUS_SEARCH_COMPLETE, gkusbFiles);
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_ALL_FILE: { // 搜索所有的文件名
                List<SZUSBFile> gkusbFiles = new ArrayList<>();
                SZUSBFile[] usbFileArr0 = new SZUSBFile[CONSTANT.MAX_FILES];
                int count0 = SZUSBSDK.GKUSB_GetAllFile(__hDevice, usbFileArr0);
                if (count0 != -1) {// -1失败，否则成功
                    for (int i = 0; i < count0; i++) {
                        gkusbFiles.add(usbFileArr0[i]);
                    }
                }

                long time = System.currentTimeMillis();
                Collections.sort(gkusbFiles, new Comparator<SZUSBFile>() {
                    @Override
                    public int compare(SZUSBFile o1, SZUSBFile o2) {
                        byte[] s1 = o2.__name;
                        byte[] s2 = o1.__name;
                        int n1 = s1.length;
                        int n2 = s2.length;
                        int min = Math.min(n1, n2);
                        for (int i = 0; i < min; i++) {
                            byte c1 = s1[i];
                            byte c2 = s2[i];
                            if (c1 != c2) {
                                return c1 - c2;
                            }
                        }
                        return n1 - n2;
                    }
                });
                notifyBusMessage(BUS_MESSAGE.BUS_SEARCH_ALL_FILE, gkusbFiles);
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_FILEINFO: { // 获取文件信息
                SZUSBFile usbFile = (SZUSBFile) msg.message;
                String name = new String(usbFile.__name) + '\0';

                SZUSBFileInfo usbFileInfo;
                usbFileInfo = (SZUSBFileInfo) SZUSBSDK.GKUSB_GetFileInfoEx(__hDevice,
                        usbFile.__lock, name.getBytes());

                if (usbFileInfo != null) {
                    usbFileInfo.__type = usbFile.__lock;
                    LogUtils.i("System", new String(usbFileInfo.__thumb_name));
                }
                notifyBusMessage(BUS_MESSAGE.BUS_FILEINFO_OK, usbFileInfo);
                break;
            }
            case CONSTANT.COMMAND.CMD_FILE_CONTROL: { // 文件的控制(视频/音频)

                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';
                byte[] bytes = name.getBytes();
                byte[] param = Arrays.copyOf(bytes, 62);
                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock, file.__command, param);
                file.__name = param;
                if (ret == -1 || ret == 1) {// 失败
                    notifyBusMessage(BUS_MESSAGE.BUS_CONTROL_ERR, file);
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_CONTROL_OK, file);
                }

                break;
            }
            case CONSTANT.COMMAND.CMD_PLAYBACK_PROGRESS: { // 获取播放进度

                int curTime = SZUSBSDK.GKUSB_GetCurrentPlaybackTime(__hDevice);
                if (curTime != -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_PLAYBACK_PROGRESS, curTime);
                }

                break;
            }
            case CONSTANT.COMMAND.CMD_GETLOCK_PROGRESS: { // 获取加锁进度
                int ret = SZUSBSDK.GKUSB_GetCurrentStatus(__hDevice,
                        SZUSBCommand.STATUS_CONTROL.STATUS_HURRY_FINISH);
                notifyBusMessage(BUS_MESSAGE.BUS_RECORD_HURRY, ret);
                break;
            }
            case CONSTANT.COMMAND.CMD_DELETE_PHOTO: {

                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';
                LogUtils.i("GKDevice", "CMD_DELETE_PHOTO type:" + file.__lock + " name:" + name);
                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock,
                        SZUSBCommand.PHOTO_FILE_CONTROL.CONTROL_DELETE, name.getBytes());
                LogUtils.i("GKDevice", "CMD_DELETE_PHOTO complete:" + ret);
                if (ret == -1 || ret == 1) {// 失败
                    notifyBusMessage(BUS_MESSAGE.BUS_DELETE_PHOTO_ERR, new String(file.__name));
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_DELETE_PHOTO, ret);
                }
                break;
            }
            case CONSTANT.COMMAND.CMD_DELETE_VIDEO: {

                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';
                LogUtils.i("GKDevice", "CMD_DELETE_VIDEO type:" + file.__lock + " name:" + name);
                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_DELETE, name.getBytes());
                LogUtils.i("GKDevice", "CMD_DELETE_VIDEO complete:" + ret);
                if (ret == -1 || ret == 1) {// 失败
                    notifyBusMessage(BUS_MESSAGE.BUS_DELETE_VIDEO_ERR, new String(file.__name));
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_DELETE_VIDEO, ret);
                }
                break;
            }
            case CONSTANT.COMMAND.CMD_LOCK_VIDEO: {
                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';
                //LogUtils.i("GKDevice","CMD_LOCK_VIDEO type:"+file.__type+" name:"+name);
                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_LOCK, name.getBytes());
                if (ret == -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_LOCK_VIDEO_ERR, new String(file.__name));
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_LOCK_VIDEO, ret);
                }
                break;
            }
            case CONSTANT.COMMAND.CMD_UNLOCK_VIDEO: {
                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';
                //LogUtils.i("GKDevice","CMD_LOCK_VIDEO type:"+file.__type+" name:"+name);
                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_UNLOCK, name.getBytes());
                if (ret == -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_UNLOCK_VIDEO_ERR, new String(file.__name));
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_UNLOCK_VIDEO, ret);
                }
                break;
            }
            case CONSTANT.COMMAND.CMD_PLAYBACK: {
                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';
                //LogUtils.i("GKDevice","CMD_LOCK_VIDEO type:"+file.__type+" name:"+name);
                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_PLAY, name.getBytes());
                if (ret == -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_PLAYBACK_ERR, new String(file.__name));
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_PLAYBACK, file);
                }
                LogUtils.i("GKDevice", "CMD_PLAYBACK ret:" + ret + " name:" + name);
                break;
            }
            case CONSTANT.COMMAND.CMD_STOP_PLAYBACK: {
                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';

                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_STOP, name.getBytes());
                if (ret == -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_STOP_PLAYBACK_ERR, new String(file.__name));
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_STOP_PLAYBACK, ret);
                }
                LogUtils.i("GKDevice", "CMD_STOP_PLAYBACK ret:" + ret + " name:" + name);
                break;
            }
            case CONSTANT.COMMAND.CMD_ENTER_FILELIST: {
                LogUtils.i("filelist", "-------enter filelist");
                if (Build.MODEL.toLowerCase().contains("sofia") || Build.MODEL.toLowerCase().contains("k1s")) {
                    notifyBusMessage(BUS_MESSAGE.BUS_ENTER_FILELIST, 1);
                    break;
                }
                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, SZUSBCommand.FILE_TYPE.CYCLE_FILE,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_ENTER_FILELIST, new byte[]{});
                LogUtils.i("filelist", "-------ret:" + ret);
                notifyBusMessage(BUS_MESSAGE.BUS_ENTER_FILELIST, ret);
                break;
            }
            case CONSTANT.COMMAND.CMD_EXIT_FILELIST: {
                LogUtils.i("filelist", "-------exit filelist");
                if (Build.MODEL.toLowerCase().contains("sofia") || Build.MODEL.toLowerCase().contains("k1s")) {
                    notifyBusMessage(BUS_MESSAGE.BUS_EXIT_FILELIST, 1);
                    break;
                }
                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, SZUSBCommand.FILE_TYPE.CYCLE_FILE,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_EXIT_FILELIST, new byte[]{});
                LogUtils.i("filelist", "-------ret:" + ret);
                notifyBusMessage(BUS_MESSAGE.BUS_EXIT_FILELIST, ret);
                break;
            }
            case CONSTANT.COMMAND.CMD_PAUSE_PLAYBACK: {
                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';

                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_PAUSE, name.getBytes());
                if (ret == -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_PAUSE_PLAYBACK_ERR, new String(file.__name));
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_PAUSE_PLAYBACK, ret);
                }
                break;
            }
            case CONSTANT.COMMAND.CMD_RESUME_PLAYBACK: {
                SZUSBFile file = (SZUSBFile) msg.message;
                String name = new String(file.__name) + '\0';

                int ret = SZUSBSDK.GKUSB_FileControl(__hDevice, file.__lock,
                        SZUSBCommand.VIDEO_FILE_CONTROL.CONTROL_RESUM, name.getBytes());
                if (ret == -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_RESUME_PLAYBACK_ERR, new String(file.__name));
                } else {
                    notifyBusMessage(BUS_MESSAGE.BUS_RESUME_PLAYBACK, ret);
                }
                break;
            }
            case CONSTANT.COMMAND.CMD_GET_PHOTO: {
                SZUSBFile file = (SZUSBFile) msg.message;
                SZUSBIFrame frame = new SZUSBIFrame();
                byte[] bytes = file.__name;
                frame.__type = file.__lock;
                String name = new String(bytes) + '\0';
                int ret = SZUSBSDK.GKUSB_GetSmallPicture(__hDevice, frame.__type, name.getBytes(), frame);
                if (ret != 0) {
                    notifyBusMessage(BUS_MESSAGE.BUS_SMALL_PHOTO_ERR, frame);
                } else {
                    LogUtils.i("GKDevice", "get photo:" + frame.__iFrame[0] + " " + frame.__iFrame[1]);
                    notifyBusMessage(BUS_MESSAGE.BUS_SMALL_PHOTO, frame);
                }

                break;
            }
            case CONSTANT.COMMAND.CMD_GET_VIDEO_THUMB: {
                SZUSBFileInfo fileInfo = (SZUSBFileInfo) msg.message;
                SZUSBIFrame frame = new SZUSBIFrame();
                byte[] bytes = fileInfo.__thumb_name;
                frame.__type = fileInfo.__type;
                String name = new String(bytes) + '\0';
                //视频缩略图为h264第一帧，需要额外的解码库。暂不支持获取视频缩略图
                int ret = SZUSBSDK.GKUSB_GetSmallPicture(__hDevice, frame.__type, name.getBytes(), frame);
                if (ret != 0) {
                    notifyBusMessage(BUS_MESSAGE.BUS_VIDEO_THUMB_ERR, name);
                } else {
                    LogUtils.i("GKDevice", "get photo:" + frame.__iFrame[0] + " " + frame.__iFrame[1]);
                    notifyBusMessage(BUS_MESSAGE.BUS_VIDEO_THUMB, frame);
                }

                break;
            }
            case CONSTANT.COMMAND.CMD_OPEN_RECORD: { // 开录像

                int status = SZUSBSDK.GKUSB_GetRecordStatus(__hDevice);
                LogUtils.i("GKDevice", "GKUSB_GetRecordStatus ret=" + status);
                if (status == -1) {
                    notifyBusMessage(BUS_MESSAGE.BUS_SETRECORD_STATUS, -1); // status值-1表示失败
                    break;
                }
                int ret = 0;
                if (status != SZUSBCommand.STATUS_RECORD.RECORDING) {
                    PublicMethod.sleep(500);
                    ret = SZUSBSDK.GKUSB_SetRecordStatus(__hDevice, SZUSBCommand.STATUS_RECORD.RECORDING);
                }
                LogUtils.i("GKDevice", "CMD_OPEN_RECORD ret=" + ret);
                if (ret == 0) {
                    int record_status = SZUSBSDK.GKUSB_GetRecordStatus(__hDevice);
                    LogUtils.i("GKDevice", "GKUSB_GetRecordStatus ret=" + record_status);
                    if (record_status != -1) {
                        notifyBusMessage(BUS_MESSAGE.BUS_GETRECORD_STATUS, record_status);
                    }
                }
                notifyBusMessage(BUS_MESSAGE.BUS_SETRECORD_STATUS, ret); // ret为0成功，否则失败
                break;
            }
            default:
                break;
        }

    }

    // 普通指令发送线程
    private Runnable commandRunnable = new Runnable() {
        @Override
        public void run() {

            while (true) {
                //此处死循环，如有其他要求可采用select监听消息
                if (__hDevice == 0 || __gkusbCmdList.__cmdList.size() == 0) {
                    PublicMethod.sleep(1);
                    continue;
                }
                // 设备发送指令
                __lock.lock();
                CommandMessage commandMessage = __gkusbCmdList.popFirstCmd();
                if (commandMessage.command == CONSTANT.COMMAND.CMD_GET_PHOTO) {
                    //减少发送图像间隔，由于不同机型usb驱动不同，响应时间不同，如遇图片加载失败可加大发送间隔或者重试。
                    PublicMethod.sleep(10);
                } else {
                    PublicMethod.sleep(50);
                }
                HandleMessage(commandMessage);
                __lock.unlock();
                PublicMethod.sleep(1);
            }
        }
    };

    // 设备状态检测线程
    private Runnable statusRunnable = new Runnable() {
        @Override
        public void run() {

            while (true) {
                if (__hDevice == 0) {
                    PublicMethod.sleep(10);
                    continue;
                }
                // 获取录像状态
                if (__lock.tryLock()) {
                    PublicMethod.sleep(50); // 20170407155352
                    int record_status = SZUSBSDK.GKUSB_GetRecordStatus(__hDevice);
                    if (record_status != -1) {
                        notifyBusMessage(BUS_MESSAGE.BUS_GETRECORD_STATUS, record_status);
                    }
                    __lock.unlock();
                }
                PublicMethod.sleep(2000);
            }
        }
    };

    public void openStream() {
        if (__hDevice != 0) {
            LogUtils.i("System", "openStream");
            sendCommand(CONSTANT.COMMAND.CMD_ALL_FORMAT, null);
        }
    }
}
